package com.promis.widget.imgzoom;

import android.animation.Animator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import com.promis.util.CollectionUtils;
import com.promis.util.ScreenUtils;
import com.promis.widget.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jidanbo on 2018/6/7.
 */

public class FullScreenVideoPreview extends RelativeLayout {

    public static final int STATE_NORMAL = 0;
    public static final int STATE_TRANSFORM_IN = 1;
    public static final int STATE_TRANSFORM_OUT = 2;

    private int mState = STATE_NORMAL;
    private final int duration = 300;

    private ThumbnailRect originalRect;
    private Drawable thumbnail;
    private String videoUrl;
    private Rect screenRect;

    private ImageView animationIV;
    private VideoView videoView;
    private ImageView imgvThumbnail;

    public FullScreenVideoPreview(Context context, ThumbnailView thumbnailView, String videoUrl) {
        super(context);

        this.videoUrl = videoUrl;
        this.thumbnail = thumbnailView.getResource();

        this.originalRect = thumbnailView.getOriginalRect();
        this.screenRect = ScreenUtils.getScreenRect(getContext());

        setBackgroundColor(Color.TRANSPARENT);
        initSubViews();
    }

    public FullScreenVideoPreview(Context context) {
        super(context);
    }

    public FullScreenVideoPreview(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FullScreenVideoPreview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**因此View添加在Window，点击手机返回按钮无法响应，
     * 重写此方法可以处理点击手机返回的逻辑处理，缩小图片到原位置
     * @param event
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {//2-4
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (mState == STATE_TRANSFORM_IN) {
                startTransform(STATE_TRANSFORM_OUT);
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean dispatchKeyEventPreIme(KeyEvent event) {//1-3
        return super.dispatchKeyEventPreIme(event);
    }


    private WindowManager windowManager;
    private void initSubViews() {
        initImageListBgView();
        initAnimationIV();
        initVideoView();
        initThumbnailIV();

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                startTransform(STATE_TRANSFORM_OUT);
            }
        });
    }

    private void initImageListBgView() {
        Activity activity = (Activity) getContext();
        windowManager = activity.getWindowManager();
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();

        Rect rect = ScreenUtils.getScreenRect(getContext());
        layoutParams.width = rect.width();
        layoutParams.height = rect.height();
        //FLAG_LAYOUT_IN_SCREEN
        layoutParams.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        layoutParams.format = PixelFormat.RGBA_8888;//让背景透明，放大过程可以看到当前界面
        layoutParams.verticalMargin = 0;
        windowManager.addView(this,layoutParams);
    }

    private void initAnimationIV() {
        animationIV = new ImageView(getContext());
//        animationIV.setScaleType(ImageView.ScaleType.FIT_CENTER);
//        LayoutParams params = new LayoutParams(originalRect.getWidth(),originalRect.getHeight());
//        params.leftMargin = originalRect.getLeft();
//        params.topMargin = originalRect.getTop();
//        addView(animationIV, params);
        animationIV.setScaleType(ImageView.ScaleType.FIT_CENTER);
        LayoutParams layoutParams = new LayoutParams(screenRect.width(), screenRect.height());
        layoutParams.addRule(CENTER_IN_PARENT);
        addView(animationIV, layoutParams);

        animationIV.setImageDrawable(thumbnail);
//        Glide.with(getContext()).load(imageUrls.get(currentIndex)).dontAnimate().into(new ImageViewTarget(animationIV));
//        Picasso.with(getContext()).load(imageUrls.get(currentIndex)).into(animationIV);
    }

    private void initVideoView() {
        videoView = new VideoView(getContext());
        videoView.setBackgroundColor(Color.parseColor("#000000"));
        LayoutParams vvLayoutParams = new LayoutParams(screenRect.width(), screenRect.height());
        vvLayoutParams.addRule(CENTER_IN_PARENT);
        addView(videoView, vvLayoutParams);

        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                if (mediaPlayer != null)
                    mediaPlayer.start();
            }
        });

        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {
                        if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                            videoView.setBackgroundColor(Color.parseColor("#00FFFFFF"));
                            imgvThumbnail.setVisibility(GONE);
                        }
                        return true;
                    }
                });
                mediaPlayer.start();

            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                startTransform(STATE_TRANSFORM_OUT);
                return false;
            }
        });

//        videoView.setOnTouchListener(new OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                startTransform(STATE_TRANSFORM_OUT);
//                return false;
//            }
//        });

        Uri uri = Uri.parse(videoUrl);
        videoView.setVideoURI(uri);
    }

    private void initThumbnailIV() {
        imgvThumbnail = new ImageView(getContext());
        imgvThumbnail.setScaleType(ImageView.ScaleType.FIT_CENTER);
        LayoutParams layoutParams = new LayoutParams(screenRect.width(), screenRect.height());
        layoutParams.addRule(CENTER_IN_PARENT);
        addView(imgvThumbnail, layoutParams);

        imgvThumbnail.setImageDrawable(thumbnail);
    }

    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            videoView.setVisibility(VISIBLE);
            imgvThumbnail.setVisibility(VISIBLE);
            animationIV.setVisibility(INVISIBLE);
        }
    };

    /**放大缩小动画
     * @param state
     */
    public void startTransform(final int state) {

        ValueAnimator valueAnimator = new ValueAnimator();
        valueAnimator.setDuration(duration);
        valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        if (state == STATE_TRANSFORM_IN) {
            setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            mState = STATE_TRANSFORM_IN;
            videoView.setVisibility(INVISIBLE);
            imgvThumbnail.setVisibility(INVISIBLE);
//            PropertyValuesHolder scaleHolder = PropertyValuesHolder.ofFloat("scale", mTransfrom.startScale, mTransfrom.endScale);
            PropertyValuesHolder leftHolder = PropertyValuesHolder.ofFloat("left",originalRect.getLeft(), 0);
            PropertyValuesHolder topHolder = PropertyValuesHolder.ofFloat("top", originalRect.getTop(), 0);
            PropertyValuesHolder widthHolder = PropertyValuesHolder.ofFloat("width", originalRect.getWidth(), screenRect.width());
            PropertyValuesHolder heightHolder = PropertyValuesHolder.ofFloat("height", originalRect.getHeight(), screenRect.height());
            PropertyValuesHolder alphaHolder = PropertyValuesHolder.ofInt("alpha", 0, 255);
            valueAnimator.setValues(leftHolder, topHolder, widthHolder, heightHolder, alphaHolder);
        } else {
//            setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
            videoView.setVisibility(INVISIBLE);
            imgvThumbnail.setVisibility(INVISIBLE);
            animationIV.setVisibility(VISIBLE);
            setBackgroundColor(Color.TRANSPARENT);
            mState = STATE_TRANSFORM_OUT;
//            PropertyValuesHolder scaleHolder = PropertyValuesHolder.ofFloat("scale", mTransfrom.endScale, mTransfrom.startScale);
            PropertyValuesHolder leftHolder = PropertyValuesHolder.ofFloat("left", animationIV.getLeft(), originalRect.getLeft());
            PropertyValuesHolder topHolder = PropertyValuesHolder.ofFloat("top", animationIV.getTop(), originalRect.getTop());
            PropertyValuesHolder widthHolder = PropertyValuesHolder.ofFloat("width", animationIV.getWidth(), originalRect.getWidth());
            PropertyValuesHolder heightHolder = PropertyValuesHolder.ofFloat("height", animationIV.getHeight(), originalRect.getHeight());
            PropertyValuesHolder alphaHolder = PropertyValuesHolder.ofInt("alpha", 255, 0);
            valueAnimator.setValues(leftHolder, topHolder, widthHolder, heightHolder, alphaHolder);
        }

        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public synchronized void onAnimationUpdate(ValueAnimator animation) {
                //                mTransfrom.scale = (Float) animation.getAnimatedValue("scale");
                Float left = (Float) animation.getAnimatedValue("left");
                Float top = (Float) animation.getAnimatedValue("top");
                Float width = (Float) animation.getAnimatedValue("width");
                Float height = (Float) animation.getAnimatedValue("height");
                Integer mBgAlpha = (Integer) animation.getAnimatedValue("alpha");

                LayoutParams layoutParams = new LayoutParams(width.intValue(),height.intValue());
                layoutParams.leftMargin = left.intValue();
                layoutParams.topMargin = top.intValue();
                animationIV.setLayoutParams(layoutParams);
                setAlpha(mBgAlpha);
            }
        });

        valueAnimator.addListener(new ValueAnimator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                /*
                 * 如果是进入的话，当然是希望最后停留在center_crop的区域。但是如果是out的话，就不应该是center_crop的位置了
                 * ， 而应该是最后变化的位置，因为当out的时候结束时，不回复视图是Normal，要不然会有一个突然闪动回去的bug
                 */
                // TODO 这个可以根据实际需求来修改
                if (mState == STATE_TRANSFORM_IN) {
                    videoView.seekTo(0);
                    setBackgroundColor(Color.BLACK);
                    handler.sendEmptyMessageDelayed(0, duration);
                } else if (mState == STATE_TRANSFORM_OUT) {
                    removeView(animationIV);
                    animationIV = null;
                    removeView(videoView);
                    videoView = null;
                    removeView(imgvThumbnail);
                    imgvThumbnail = null;
                    windowManager.removeView(FullScreenVideoPreview.this);
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }
        });
        valueAnimator.start();
    }
}
